﻿using System.Collections.Generic;
using Microsoft.SharePoint;

namespace OpenWaves.ActivityFeed.Sharepoint
{
    public class ActivityFeedSharepointConnectorBase : IActivityFeedSharepointConnector
    {
        private readonly IActivityFeedService activityFeedService;

        public ActivityFeedSharepointConnectorBase(IActivityFeedService activityFeedService)
        {
            this.activityFeedService = activityFeedService;
        }

        public void OnItemEvent(SPItemEventProperties properties, SPEventReceiverType eventType)
        {
            this.activityFeedService.PublishUpdate(
                this.GetUpdateContent(properties, eventType),
                this.GetUserName(properties),
                this.GetSourceName(properties, eventType),
                this.GetTopics(properties), 
                false,  //IsPublic
                this.GetUserGroups(properties));
        }

        protected virtual string GetSourceName(SPItemEventProperties properties, SPEventReceiverType eventType)
        {
            return "Sharepoint";
        }

        protected virtual string GetUserName(SPItemEventProperties properties)
        {
            return properties.UserLoginName;
        }

        protected virtual IEnumerable<UserGroup> GetUserGroups(SPItemEventProperties properties)
        {
            var roles = new List<UserGroup>();
            foreach (SPRoleAssignment roleAssignment in properties.List.RoleAssignments)
            {
                roles.Add(UserGroup.FromRole(roleAssignment.Member.LoginName));
                /*
                foreach (SPRoleDefinition roleDefinitionBinding in roleAssignment.RoleDefinitionBindings)
                {
                    //roleDefinitionBinding.Type = SPRoleType.Reader;
                    var test = roleDefinitionBinding.Type;
                    roles.Add(UserGroup.FromRole(roleDefinitionBinding.Name));
                }
                */
            }
            return roles;
        }

        protected virtual IEnumerable<Topic> GetTopics(SPItemEventProperties properties)
        {
            return new Topic[]
                       {
                           properties.List.AsTopic(), 
                           properties.Web.AsTopic(), 
                           properties.Web.Site.AsTopic(),
                           properties.Web.AllUsers.GetByID(properties.CurrentUserId).AsTopic()
                       }; 
        }

        protected virtual UpdateContent GetUpdateContent(SPItemEventProperties properties, SPEventReceiverType eventType)
        {
            return new SpListItemContent
            {
                Title = properties.ListItem.DisplayName,
                Url = properties.ListItem.Url,
                EventType =  eventType,
                ListTemplate = properties.List.BaseTemplate
            };
        }
    }
}